package com.example.wordtext.utils;

import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Map;

/**
 *
 * @author weijingchen
 * @DateTime 2025-08-26
 */
@Slf4j
public class WordDocUtil {

    private static final String TEMPLATE_PATH = "templates/徐工设备贷业务回购贷款业务通知书.doc";
    private static final String DEFAULT_FILENAME_PREFIX = "徐工设备贷业务回购贷款业务通知书";

    /**
     * 填充Word模板
     *
     * @param data 填充数据
     */
    public static void fillTemplate(HttpServletResponse response, Map<String, String> data) {
        if (data == null) {
            log.warn("填充数据为空，无法生成文档");
            return;
        }

        try (InputStream is = WordDocUtil.class.getClassLoader().getResourceAsStream(TEMPLATE_PATH);
             OutputStream out = response.getOutputStream()) {
            if (is == null) {
                log.error("在路径中找不到Word模板: {}", TEMPLATE_PATH);
                return;
            }

            HWPFDocument document = new HWPFDocument(is);

            // 替换文档中的文本
            replaceInDocument(document, data);


            // 6. 设置响应头
            response.setContentType("application/octet-stream;charset=utf-8");
            String filename = DEFAULT_FILENAME_PREFIX + data.get("序号") + ".doc";
            String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8);
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFilename);

            // 直接将模板写入响应输出流
            document.write(out);


        } catch (IOException e) {
            log.error("生成或发送文件时出错", e);
        }

    }

    /**
     * 在HWPF文档中替换占位符
     */
    private static void replaceInDocument(HWPFDocument document, Map<String, String> data) {
        Range range = document.getRange();

        // 直接在整个文档范围内替换所有占位符
        for (Map.Entry<String, String> entry : data.entrySet()) {
            String placeholder = "${" + entry.getKey() + "}";
            String value = entry.getValue();

            try {
                // 循环替换，确保所有匹配项都被替换
                while (range.text().contains(placeholder)) {
                    range.replaceText(placeholder, value);
                }
            } catch (Exception e) {
                log.error("替换占位符失败: " + placeholder + " - " + e.getMessage());
            }
        }
    }
}
